package org.dromara.bykt.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HtmlUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.bykt.domain.bo.BYKTCourseQuestionsBo;
import org.dromara.bykt.domain.bo.BYKTCourseSimulationBo;
import org.dromara.bykt.domain.vo.BYKTCourseSimulationImportVo;
import org.dromara.bykt.domain.vo.BYKTCourseSimulationVo;
import org.dromara.bykt.service.*;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class BYKTCourseSimulationImportListener extends AnalysisEventListener<BYKTCourseSimulationImportVo> implements ExcelListener<BYKTCourseSimulationImportVo> {

    private final IBYKTCourseSimulationService courseSimulationService;

    private final IBYKTSimulationInfoService simulationInfoService;

    private final IBYKTCourseService courseService;

    private final IBYKTCourseVideoService courseVideoService;

    private final Boolean isUpdateSupport;

    private final Map<String, String> pictureMap;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    ObjectMapper objectMapper = new ObjectMapper();
    String[] optionLetters = {"A", "B", "C", "D", "E", "F", "G"};

    public BYKTCourseSimulationImportListener(Boolean isUpdateSupport, Map<String, String> pictureMap) {
        this.courseSimulationService = SpringUtils.getBean(IBYKTCourseSimulationService.class);
        this.courseService = SpringUtils.getBean(IBYKTCourseService.class);
        this.courseVideoService = SpringUtils.getBean(IBYKTCourseVideoService.class);
        this.simulationInfoService = SpringUtils.getBean(IBYKTSimulationInfoService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.pictureMap = pictureMap;
    }

    @Override
    public void invoke(BYKTCourseSimulationImportVo courseSimulationImportVo, AnalysisContext context) {
        BYKTCourseSimulationVo byktCourseSimulationVo = this.courseSimulationService.selectText(courseSimulationImportVo.getTitle());
        // 获取当前行的图片索引（需要根据实际情况调整）
        int pictureIndex = context.readRowHolder().getRowIndex() - 1;
        try {
            // 处理图片引用
            if (courseSimulationImportVo.getImage() != null) {
                if (courseSimulationImportVo.getImage().startsWith("=_xlfn.DISPIMG(") || courseSimulationImportVo.getImage().startsWith("=DISPIMG(")) {
                    // 使用行号作为key获取对应的图片URL
                    String ossUrl = pictureMap.get("picture_" + pictureIndex);
                    if (ossUrl != null) {
                        courseSimulationImportVo.setImage(ossUrl);
                    }
                }
            }
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(byktCourseSimulationVo)) {
                BYKTCourseSimulationBo simulationBo = BeanUtil.toBean(courseSimulationImportVo, BYKTCourseSimulationBo.class);
                ValidatorUtils.validate(simulationBo);
                if (courseSimulationImportVo.getVideoName() != null && !courseSimulationImportVo.getVideoName().isEmpty()) {
                    Long l = courseVideoService.selectVideoName(courseSimulationImportVo.getVideoName());
                    if (l != 0L) {
                        simulationBo.setVideoId(l);
                    }
                }
                if (courseSimulationImportVo.getCourseName() != null && !courseSimulationImportVo.getCourseName().isEmpty()) {
                    Long l = courseService.selectCourseName(courseSimulationImportVo.getCourseName());
                    if (l != 0L) {
                        simulationBo.setCourseId(l);
                    }
                }
                if (courseSimulationImportVo.getSimulationName() != null && !courseSimulationImportVo.getSimulationName().isEmpty()) {
                    Long l = simulationInfoService.selectSimulationName(courseSimulationImportVo.getSimulationName());
                    if (l != 0L) {
                        simulationBo.setSimulationId(l);
                    }
                }
                List<Map<String, String>> optionsList = new ArrayList<>();
                for (String letter : optionLetters) {
                    String optionId = (String) courseSimulationImportVo.getClass()
                        .getMethod("getOption" + letter)
                        .invoke(courseSimulationImportVo);

                    String optionText = (String) courseSimulationImportVo.getClass()
                        .getMethod("getOption" + letter + "Text")
                        .invoke(courseSimulationImportVo);

                    if (optionId != null && !optionId.isEmpty()) {
                        Map<String, String> optionMap = new HashMap<>();
                        optionMap.put("id", optionId);
                        optionMap.put("text", optionText);
                        optionsList.add(optionMap);
                    }
                }

                String jsonArray = objectMapper.writeValueAsString(optionsList);
                simulationBo.setOptions(jsonArray);
                if (courseSimulationImportVo.getType() != null && !courseSimulationImportVo.getType().isEmpty()) {
                    if ("单选".equals(courseSimulationImportVo.getType())) {
                        simulationBo.setType("0");
                    }
                    if ("多选".equals(courseSimulationImportVo.getType())) {
                        simulationBo.setType("1");
                    }
                    if ("判断".equals(courseSimulationImportVo.getType())) {
                        simulationBo.setType("2");
                    }
                    if ("简答".equals(courseSimulationImportVo.getType())) {
                        simulationBo.setType("3");
                    }
                }
                if (courseSimulationImportVo.getQuestionType() != null && !courseSimulationImportVo.getQuestionType().isEmpty()) {
                    if ("习题".equals(courseSimulationImportVo.getQuestionType())) {
                        simulationBo.setQuestionType("1");
                    }
                    if ("刷题".equals(courseSimulationImportVo.getQuestionType())) {
                        simulationBo.setQuestionType("2");
                    }
                    if ("考试".equals(courseSimulationImportVo.getQuestionType())) {
                        simulationBo.setQuestionType("3");
                    }
                }
                if (courseSimulationImportVo.getSort() != null && !"".equals(courseSimulationImportVo.getSort())) {
                    simulationBo.setSort(Long.valueOf(courseSimulationImportVo.getSort()));
                }

                courseSimulationService.insertByBo(simulationBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(simulationBo.getTitle()).append(" 导入成功");
            } else if (isUpdateSupport) {
                BYKTCourseSimulationBo simulationBo = BeanUtil.toBean(courseSimulationImportVo, BYKTCourseSimulationBo.class);
                simulationBo.setId(byktCourseSimulationVo.getId());
                if (courseSimulationImportVo.getVideoName() != null && !courseSimulationImportVo.getVideoName().isEmpty()) {
                    Long l = courseVideoService.selectVideoName(courseSimulationImportVo.getVideoName());
                    if (l != 0L) {
                        simulationBo.setVideoId(l);
                    }
                }
                if (courseSimulationImportVo.getCourseName() != null && !courseSimulationImportVo.getCourseName().isEmpty()) {
                    Long l = courseService.selectCourseName(courseSimulationImportVo.getCourseName());
                    if (l != 0L) {
                        simulationBo.setCourseId(l);
                    }
                }
                List<Map<String, String>> optionsList = new ArrayList<>();
                for (String letter : optionLetters) {
                    String optionId = (String) courseSimulationImportVo.getClass()
                        .getMethod("getOption" + letter)
                        .invoke(courseSimulationImportVo);

                    String optionText = (String) courseSimulationImportVo.getClass()
                        .getMethod("getOption" + letter + "Text")
                        .invoke(courseSimulationImportVo);

                    if (optionId != null && !optionId.isEmpty()) {
                        Map<String, String> optionMap = new HashMap<>();
                        optionMap.put("id", optionId);
                        optionMap.put("text", optionText);
                        optionsList.add(optionMap);
                    }
                }

                String jsonArray = objectMapper.writeValueAsString(optionsList);
                simulationBo.setOptions(jsonArray);
                if (courseSimulationImportVo.getQuestionType() != null && !courseSimulationImportVo.getQuestionType().isEmpty()) {
                    if ("习题".equals(courseSimulationImportVo.getQuestionType())) {
                        simulationBo.setQuestionType("1");
                    }
                    if ("刷题".equals(courseSimulationImportVo.getQuestionType())) {
                        simulationBo.setQuestionType("2");
                    }
                    if ("考试".equals(courseSimulationImportVo.getQuestionType())) {
                        simulationBo.setQuestionType("3");
                    }
                }
                courseSimulationService.updateByBo(simulationBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(simulationBo.getTitle()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(courseSimulationImportVo.getTitle()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + HtmlUtil.cleanHtmlTag(courseSimulationImportVo.getTitle()) + " 导入失败：";
            String message = e.getMessage();
            if (e instanceof ConstraintViolationException cvException) {
                message = StreamUtils.join(cvException.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
            }
            failureMsg.append(msg).append(message);
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<BYKTCourseSimulationImportVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<BYKTCourseSimulationImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
